package com.fintech.third.service.shzx;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.fintech.common.enums.RespStatus;
import com.fintech.common.service.BaseServiceImpl;
import com.fintech.common.util.PropertiesUtils;
import com.fintech.datagroud.dao.shzx.EdcZxPersonalBaoGaoInfoMapper;
import com.fintech.datagroud.service.EdcZxPersonalService;
import com.fintech.third.constant.LocalStatus;
import com.fintech.third.constant.ThirdMethodConstants;
import com.fintech.third.edczxutil.util.UtilXmlBean;
import com.fintech.third.model.EdcDataQueryLog;
import com.fintech.third.model.ThirdEffectDTO;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.shzx.EdcZxPersonalInfo;
import com.fintech.third.model.shzx.EdcZxPersonalLoanOrderInfo;
import com.fintech.third.model.shzx.EdcZxPersonalNewCredit;
import com.fintech.third.model.shzx.EdcZxQueryMessageRecordsInfo;
import com.fintech.third.service.credit.CreditReportService;
import com.fintech.third.utils.SerialNumCreater;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.fintech.third.utils.ThirdSystemUtil;
import com.fintech.third.utils.common.RequestResult;
import com.fintech.third.utils.common.SendHttpRequestUtil;
import com.marvels.common.utils.MarvelsLogUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import net.sf.json.JSONObject;

/**
 * 登录上海征信接口
 * 
 * @author xiongxianghua
 *
 *         2017年11月27日
 */

@Service("shangHaiLogInServiceImpl")
public class ShangHaiLogInImpl extends BaseServiceImpl implements ShangHaiLogInService {

	static Cookie[] cookies = {};

	final static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

	final static HttpClient httpClient = new HttpClient(connectionManager);

	@Autowired
	private EdcZxPersonalService edcZxPersonalService;
	@Autowired
	private EdcZxPersonalBaoGaoInfoMapper edcZxPersonalBaoGaoInfoMapper;
	@Autowired
	private CreditReportService creditReportService;
	
	private void shanghailoginVPN(HttpClient httpClient) throws Exception {
		MarvelsLogUtil.getInstance().info("==========shanghailoginVPN====start========");
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		System.setProperty("javax.net.ssl.trustStore",
				ThirdSystemUtil.class.getResource(thirdProperties.getShzx_certificate_url()).getPath());
		String step1Url = thirdProperties.getShzx_step1_url();
		String step2Url = thirdProperties.getShzx_step2_url();
		MarvelsLogUtil.getInstance().info("==========shanghailoginVPN====step1Url========: " + step1Url);
		// STEP1:
		HttpClientParams httparams = new HttpClientParams();
		httparams.setSoTimeout(30000);
		httpClient.setParams(httparams);

		httpClient.getHostConfiguration().setHost("vpn.shanghai-cis.com.cn", 80);

		PostMethod login = new PostMethod(step1Url);
		login.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		httpClient.executeMethod(login);

		MarvelsLogUtil.getInstance().info("==========Cookies step1Url============");
		httpClient.getState().addCookies(httpClient.getState().getCookies());
		login.releaseConnection();

		// STEP2:
		PostMethod login2 = new PostMethod(step2Url);
		login2.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		login2.addRequestHeader("Refer", step1Url);
		login2.addRequestHeader("Accept",
				"image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");

		NameValuePair tgroup = new NameValuePair("tgroup", "");
		NameValuePair next = new NameValuePair("next", "");
		NameValuePair tgcookieset = new NameValuePair("tgcookieset", "");
		NameValuePair Login = new NameValuePair("Login", "登录");
		NameValuePair Email = new NameValuePair("username", thirdProperties.getShzx_user_name());
		NameValuePair password1 = new NameValuePair("password", thirdProperties.getShzx_pass_word());
		// NameValuePair code = new NameValuePair( "code"
		// ,"????");//有时候需要验证码，暂时未解决

		NameValuePair[] data = { tgroup, next, tgcookieset, Login, Email, password1 };
		login2.setRequestBody(data);

		httpClient.executeMethod(login2);

		MarvelsLogUtil.getInstance().info("==========Cookies step2Url============");
		httpClient.getState().addCookies(httpClient.getState().getCookies());
		login2.releaseConnection();
	}

	@SuppressWarnings("deprecation")
	private void queryCredit(Map<String, String> map, HttpClient httpClient) {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String thir = thirdProperties.getShzx_url_prefix();
		String batchcreditwebservice = thirdProperties.getShzx_batchcreditwebservice_uri();
		thir = thir + batchcreditwebservice;

		String orgcode = thirdProperties.getShzx_org_code();
		String ssecret = thirdProperties.getShzx_sse_cret();
		// 例子4： 信用报告单笔查询接口
		PostMethod login7 = new PostMethod(thir);

		String name = map.get("name");
		String cardNo = map.get("certno");
		Date requestDate = new Date();
		Date responseDate = null;
		String responseCode = "";
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		MarvelsLogUtil.getInstance().info("=========queryCredit请求上海征信入参为： " + map.toString());
		String generateOrderNo = map.get("generateOrderNo");
		EdcZxQueryMessageRecordsInfo recordsInfo = assembleMessageRecords(map);

		try {
			login7.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			login7.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			String reuqest7 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.creditreport.p2p.sino.com/\">"
					+ "<soapenv:Header/>" + "<soapenv:Body>" + "<web:queryCredit>" + "<orgcode>" + orgcode
					+ "</orgcode>" + "<secret>" + ssecret + "</secret>" + "<plate>1</plate>" + "<certtype>0</certtype>"
					+ "<certno>" + cardNo + "</certno>" + "<name>" + name + "</name>" + "<reason>02</reason>"
					+ "<createtype>1</createtype>" + "</web:queryCredit>" + "</soapenv:Body>" + "</soapenv:Envelope>";

			long time1 = System.currentTimeMillis();

			MarvelsLogUtil.getInstance().info(time1 + " 组成访问上海征信请求数据为queryCredit：   " + reuqest7.toString());

			login7.setRequestBody(reuqest7);
			httpClient.executeMethod(login7);
			String result7 = getReturnInfo(login7);
			responseDate = new Date();
			long time2 = System.currentTimeMillis();
			MarvelsLogUtil.getInstance().info((time2 - time1) + "  ====---result7---====上海征信返回报文：  " + result7);

			String str = result7;
			JSONObject json = convertSoapToJson(str);

			String state = json.get("state") + "";
			responseCode = state;
			if ("1".equals(state)) { // 查询到结果
				status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 先设置成落库失败，如果落库成功，就改为成功有数据
				String xmlStr = convertSoapToXML(result7);
				MarvelsLogUtil.getInstance().info("==========deal after xml：  " + xmlStr);
				Document document = DocumentHelper.parseText(xmlStr);
				// 解析报文后，返回的bean对象
				EdcZxPersonalInfo info = UtilXmlBean.XmlUtilBean(document);

				MarvelsLogUtil.getInstance().info("解析返回报文入库数据为EdcZxPersonalInfo ：  " + com.alibaba.fastjson.JSONObject.toJSONString(info));
				if (null != info) {
					try {
						edcZxPersonalService.creditPersonalReport(info, map, generateOrderNo);
						// 报告编号
						recordsInfo.setReportNo(info.getPersonalBasic().getReportNo());
						recordsInfo.setStatu("1");
						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 落库成功，改为成功有数据
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error("上海征信落库失败", e);
						// 报告编号
						recordsInfo.setReportNo(info.getPersonalBasic().getReportNo());
						recordsInfo.setStatu("0");
					}
				}
			} else if ("2".equals(state)) { // 被查询人不存在
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				recordsInfo.setStatu("2");
				recordsInfo.setError("被查询人不存在");
			} else { // 其它错误
				status = LocalStatus.CALL_SUCCESS.getCode();
				String errors = (String) json.get("errors");
				recordsInfo.setStatu("0");
				recordsInfo.setError(errors);
				MarvelsLogUtil.getInstance().info("上海征信查询失败记录EdcZxQueryMessageRecordsInfo：  " + recordsInfo.toString());
			}
		} catch (Exception ex) {
			MarvelsLogUtil.getInstance().error("获取上海征信数据出现异常", ex);
			recordsInfo.setStatu("0");
			recordsInfo.setError("获取上海征信数据出现异常");
		} finally {
			login7.releaseConnection();
			if (recordsInfo != null) {
				edcZxPersonalService.insertMessageRecords(recordsInfo);
			}
			EdcDataQueryLog log = QueryDataQueryLog(map.get("generateOrderNo"), "edc_shzx_data_query_log");
			if (log == null) {
				// 插入第三方数据调用日志(不同第三方不同表)
				saveDataQueryLogNew(map.get("generateOrderNo"), map.get("loanId"), null, requestDate,
						ThirdMethodConstants.SHANGHAIZX001, responseCode, status, "edc_shzx_data_query_log", cardNo);
			} else {
				// 更新第三方数据调用日志(不同第三方不同表)
				updateDataQueryLog(map.get("generateOrderNo"), map.get("loanId"), "", "", null, responseDate,
						ThirdMethodConstants.SHANGHAIZX001, responseCode, status, "edc_shzx_data_query_log", "system",
						log.getId());
			}
		}
	}

	
	@SuppressWarnings("deprecation")
	@Override
	public void queryNewDirect(Map<String, String> map) {
		String url = PropertiesUtils.getString("shzx_new_credit_url");
		String orgcode = PropertiesUtils.getString("shzx_orgcode");
		String secret = PropertiesUtils.getString("shzx_api_ssecret");
		String productId = PropertiesUtils.getString("shzx_api_product_id");
		String mobileNo = map.get("phone");
		String loanId = map.get("loanId");
		String requestId = RandomUtil.randomString(24);
		Date requestDate = new Date();
		String responseCode = null;//第三方code
		if (PropertiesUtils.isTurnOffForSwitch("switch.shanghaizx002")) {
			MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 接口禁用");
			return;
		}
		MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 原始请求参数：" + com.alibaba.fastjson.JSONObject.toJSONString(map));
		String status = LocalStatus.REQUEST_FAIL.getCode();// 默认请求失败
		EdcZxPersonalNewCredit zxPersonalNewCredit = creditReportService.getZXNewCredit(loanId);
		if(zxPersonalNewCredit != null){
			MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit　已經存在歷史記錄，不再查詢");
			return;
		}
		try {
			Map<String, String> param = new HashMap<String, String>();
			param.put("cert_name", map.get("name")); //姓名
			param.put("cert_type", "0"); //证件类型
			param.put("cert_id", map.get("certno")); //证件号码
			param.put("orgcode", orgcode); //机构代码
			param.put("secret", secret); //机构调用系统接口的认证密码
			param.put("product_id", productId); //数据产品号
			param.put("request_date", DateUtil.now()); //请求日期
			param.put("request_id", requestId); //查询机构自定义请求编号
			MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 组装后请求参数：" + com.alibaba.fastjson.JSONObject.toJSON(param));
			RequestResult requestResult = SendHttpRequestUtil.put(url, param);
			MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 请求返回值：" + com.alibaba.fastjson.JSONObject.toJSON(requestResult));
			if(requestResult != null && requestResult.getStatusCode() == 200 && !requestResult.getResult().isEmpty()){
				com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(requestResult.getResult());
				responseCode = result.getString("state_code");
				status = LocalStatus.IN_DATABASE_FAIL.getCode();
				EdcZxPersonalNewCredit edcZxPersonalNewCredit = new EdcZxPersonalNewCredit();
				edcZxPersonalNewCredit.setReqNo(requestId);
				edcZxPersonalNewCredit.setLoanId(loanId);
				edcZxPersonalNewCredit.setMobile(mobileNo);
				edcZxPersonalNewCredit.setCustIdCard(map.get("certno"));
				edcZxPersonalNewCredit.setResponseCode(responseCode);
				if("200".equals(responseCode) && result.containsKey("value")){
					MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 命中值");
					JSONArray arrayList = result.getJSONArray("value");
					for (Iterator iterator = arrayList.iterator(); iterator.hasNext();) {
						com.alibaba.fastjson.JSONObject job = (com.alibaba.fastjson.JSONObject) iterator.next();
						switch (job.getString("subproduct_id")) {
						case "P2016C0301001":
							edcZxPersonalNewCredit.setLoanAccountNumber(job.getString("subproduct_value"));
							break;
						case "P2016C0301002":
							edcZxPersonalNewCredit.setLoanContractTotal(job.getString("subproduct_value"));
							break;
						case "P2016C0301003":
							edcZxPersonalNewCredit.setLoanBalancTotal(job.getString("subproduct_value"));
							break;
						case "P2016C0503001":
							edcZxPersonalNewCredit.setLoanMechanismNumber(job.getString("subproduct_value"));
							break;
						case "P2016C0608001":
							edcZxPersonalNewCredit.setLoanOverdueTotal(job.getString("subproduct_value"));
							break;
						case "P2016C0402001":
							edcZxPersonalNewCredit.setB24LoanAccountNumber(job.getString("subproduct_value"));
							break;
						case "P2016C0403001":
							edcZxPersonalNewCredit.setB24LoanApplyNumber(job.getString("subproduct_value"));
							break;
						case "P2016C0403017":
							edcZxPersonalNewCredit.setB12LoanRefuseNumber(job.getString("subproduct_value"));
							break;
						case "P2016C0503002":
							edcZxPersonalNewCredit.setB24LoanMechanismNumber(job.getString("subproduct_value"));
							break;
						case "P2016C0601001":
							edcZxPersonalNewCredit.setB24OverdueMonths(job.getString("subproduct_value"));
							break;
						default:
							break;
						}
			        }
				}
				edcZxPersonalBaoGaoInfoMapper.insertPersonalNewCredit(edcZxPersonalNewCredit);
				status = LocalStatus.SUCCESS_WITH_DATA.getCode();
				MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 数据插入成功");
				if("604".equals(responseCode)){
					status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode();
					MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 查询成功但无数据返回");
				}else if(!"200".equals(responseCode)){
					status = LocalStatus.CALL_SUCCESS.getCode();
					MarvelsLogUtil.getInstance().info(loanId + "上海资信 new queryCredit 请求成功但返回非200状态");
				}
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(loanId + "上海资信 new queryCredit 请求异常", e);
		} finally {
			saveDataQueryLogNew(requestId, loanId, mobileNo, requestDate,
					ThirdMethodConstants.SHANGHAIZX001, responseCode, status, "edc_shzx_data_query_log", map.get("certno"));
		}
	}
	
	private EdcZxQueryMessageRecordsInfo assembleMessageRecords(Map<String, String> map) {
		EdcZxQueryMessageRecordsInfo recordsInfo = new EdcZxQueryMessageRecordsInfo();
		Date date = new Date();
		recordsInfo.setReason("02");
		recordsInfo.setCreatetype("1");
		recordsInfo.setLoanId(map.get("loanId"));
		recordsInfo.setCardType("0");
		recordsInfo.setCreatedBy("sys");
		recordsInfo.setCreatedDate(date);
		recordsInfo.setUpdatedBy("sys");
		recordsInfo.setUpdatedDate(date);
		recordsInfo.setRealName(map.get("name"));
		recordsInfo.setCardNo(map.get("certno"));
		recordsInfo.setPlate("1");
		recordsInfo.setReqNo(map.get("generateOrderNo"));
		recordsInfo.setStatu("0"); // 默认失败 0：失败 1：成功有数据 2：成功无数据
		return recordsInfo;
	}

	private String getReturnInfo(PostMethod login7) throws IOException {
		return login7.getResponseBodyAsString();
	}

	/**
	 * 解析返回报文为xml
	 * 
	 * @param result
	 * @return
	 */
	private static String convertSoapToXML(String result) {
		result = StringUtils.remove(result, "\\n");
		result = StringUtils.remove(result, "\\");
		result = StringEscapeUtils.unescapeXml(result);
		result = StringUtils.substringBetween(result, "<?xml", ">\"");
		result = "<?xml" + result + ">";
		return result;
	}

	private static JSONObject convertSoapToJson(String result) {
		result = StringUtils.remove(result, "\\");
		result = StringEscapeUtils.unescapeXml(result);
		result = StringUtils.substringBetween(result, "<return>[", "]</return>");
		String json = StringUtils.substringAfter(result, "\"state\"");
		if ("".equals(json)) {
			return new JSONObject();
		}
		json = "{\"state\"" + json;
		JSONObject objJson = JSONObject.fromObject(json);
		return objJson;
	}

	/**
	 * 查询个人征信信息
	 */
	@Override
	public EdcZxPersonalInfo queryEdcZxPersonalInfo(Map<String, String> map) {
		String reportNo = map.get("reqNo");
		EdcZxPersonalInfo info = new EdcZxPersonalInfo();
		if (!"".equals(reportNo) && null != reportNo) {
			info = edcZxPersonalService.queryEdcZxPersonalInfo(map);
		}
		return info;
	}

	/**
	 * 查询个人征信流水信息
	 */
	@Override
	public List<EdcZxQueryMessageRecordsInfo> queryMessageRecordsInfo(Map<String, String> map) {
		String loanId = map.get("loanId");
		List<EdcZxQueryMessageRecordsInfo> list = new ArrayList<EdcZxQueryMessageRecordsInfo>();
		if (!"".equals(loanId) && null != loanId) {
			list = edcZxPersonalService.queryMessageRecordsInfo(loanId);
		}
		return list;
	}

	/**
	 * 对接上海征信个人信息
	 */
	@Override
	public Map<String, String> shzxPeronalInfo(Map<String, String> map) throws Exception {
		Map<String, String> returnMap = new HashMap<String, String>();
		String loanId = map.get("loanId");
		String interfaceCode = ThirdMethodConstants.SHANGHAIZX001;
		// 获取时效性相关数据
		ThirdEffectDTO effectDto = new ThirdEffectDTO();
		effectDto.setCustIdCard(map.get("certno"));
		effectDto.setInterfaceCode(interfaceCode);
		effectDto.setLoanId(loanId);
		effectDto.setProductType(map.get("productType"));
		effectDto.setMobileNo(map.get("phone"));
		effectDto = checkEffectInfo(effectDto);
		// 实时查询
		if (QUERY_REALTIME.equals(effectDto.getEffectFlag())) {
			/*
			 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
			 */
			if (PropertiesUtils.isTurnOffForSwitch("switch.shanghaizx001")) {
				// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
				returnMap.put("code", RespStatus.DISABLE.getCode() + "");
				returnMap.put("msg", RespStatus.DISABLE.getMsg());
				return returnMap;
			}
			queryDirect(map);
		}

		// 接口停用
		if (QUERY_STOP.equals(effectDto.getEffectFlag())) {
			MarvelsLogUtil.getInstance().info("=========配置上海资信接口无效==========");
			returnMap.put("code", "0001");
			returnMap.put("msg", "接口已经暂停使用");
			return returnMap;
		}

		// 需要重新查询，并且时效性中间表要记录结果数据
		if (QUERY_REALTIME_AND_IN_RECORDS.equals(effectDto.getEffectFlag())) {
			/*
			 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
			 */
			if (PropertiesUtils.isTurnOffForSwitch("switch.shanghaizx001")) {
				// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
				returnMap.put("code", RespStatus.DISABLE.getCode() + "");
				returnMap.put("msg", RespStatus.DISABLE.getMsg());
				return returnMap;
			}
			queryDirect(map);
			saveEdcDataCallOperationRecords(effectDto);
			returnMap.put("code", "0000");
			returnMap.put("msg", "为第一次调用或数据已过有效期，需要对接第三方");
		}

		// 无需重新查询，取历史数据
		if (QUERY_HISTORY.equals(effectDto.getEffectFlag())) {
			MarvelsLogUtil.getInstance().info("==========数据属于有效期============");
			returnMap.put("code", "0000");
			returnMap.put("msg", "数据属于有限期不需要对接第三方");
		}
		return returnMap;
	}

	/**
	 * 对接上海征信个人信息
	 */
//	@Override
//	public Map<String, String> shzxPeronalInfo(Map<String, String> map) throws Exception {
//		Map<String, String> returnMap = new HashMap<String, String>();
//		MarvelsLogUtil.getInstance().info("==========shzxPeronalInfo====start========: " + map.toString());
//		// TODO待加入数据有效性教育跟接口开关校验
//
//		String productType = "";// 产品id
//		String interfaceCode = ThirdMethodConstants.SHANGHAIZX001;
//		String custIdCard = "";
//		String mobile = "";
//		String productId = "";
//		AcLoanApplyInfo queryLoanBasicInfo = loanInfoIDragonService.queryLoanBasicInfo(map.get("loanId"));
//		if (queryLoanBasicInfo != null) {
//			productType = queryLoanBasicInfo.getProductType() + "";// 产品id
//			custIdCard = queryLoanBasicInfo.getCustIdCard();
//			mobile = queryLoanBasicInfo.getMobileNum();
//		} else {
//			Map<String, String> mallMap = new HashMap<String, String>();
//			try {
//				mallMap = mallThirdService.getMallData(map.get("loanId"));
//				productId = mallThirdService.getMallParamValue("wallet_product_type_id");
//			} catch (Exception e) {
//				MarvelsLogUtil.getInstance().error("查询商城基础数据异常", e);
//			}
//			Object isBaiMi = map.get("isBaiMi");
//			if(isBaiMi != null && "bm".equals(isBaiMi.toString())){
//				productType = productId;
//				custIdCard = map.get("certno");
//				mobile = map.get("phone");
//			}else {
//				productType = mallMap.get("product_type_id");
//				custIdCard = mallMap.get("idno");
//				mobile = mallMap.get("mobile");
//			}
//			productType = mallMap.get("product_type_id");
//			custIdCard = mallMap.get("idno");
//			mobile = mallMap.get("mobile");
//		}
//		Map<String, Object> reMap = new HashMap<String, Object>();
//		reMap.put("productType", productType);
//		reMap.put("interfaceCode", interfaceCode);
//		// 先查询接口的有效期设置 如果未设置则走以前老的接口 如果设置了则判断数据存在与否及数据是否过有效期
//		EdcProductInterfaceEffecttimeConfigDto edcProductInterfaceEffecttimeConfigDto = edcProductInterfaceEffecttimeConfigMapper
//				.selectEdcProInterfaceTimeConfigSig(reMap);
//		// 这一步是，第三方数据不存着有效期的概念，直接对接第三方，获取数据
//		if (edcProductInterfaceEffecttimeConfigDto == null
//				|| (edcProductInterfaceEffecttimeConfigDto != null && edcProductInterfaceEffecttimeConfigDto.getIsUser()
//						&& edcProductInterfaceEffecttimeConfigDto.getValidityDate().equals("0"))) {
//			// 直接查询接口
//			MarvelsLogUtil.getInstance().info("=========实时调用上海资信===start==========");
//			/*
//			 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
//			 */
//			if (PropertiesUtils.isTurnOffForSwitch("switch.shanghaizx001")) {
//				// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
//				returnMap.put("code", RespStatus.DISABLE.getCode() + "");
//				returnMap.put("msg", RespStatus.DISABLE.getMsg());
//				return returnMap;
//			}
//			queryDirect(map);
//		} else if (edcProductInterfaceEffecttimeConfigDto != null
//				&& !edcProductInterfaceEffecttimeConfigDto.getIsUser()) {
//			MarvelsLogUtil.getInstance().info("=========配置上海资信接口无效==========");
//			returnMap.put("code", "0001");
//			returnMap.put("msg", "接口已经暂停使用");
//			return returnMap;
//		} else {
//			// 判断数据是否存在
//			MarvelsLogUtil.getInstance().info("==========校验数据是否属于有效期============");
//			Map<String, Object> conditionMap = new HashMap<String, Object>();
//			conditionMap.put("interfaceCode", interfaceCode);
//			conditionMap.put("custIdCard", custIdCard);
//			conditionMap.put("mobile", mobile);
//			conditionMap.put("validityEndDate", edcProductInterfaceEffecttimeConfigDto.getValidityDate());
//			EdcDataCallOperationRecordsDto edcDataCallOperationRecordsDto = edcDataCallOperationRecordsMapper
//					.selectEdcDataCallOperationRecordSig(conditionMap);
//			if (edcDataCallOperationRecordsDto == null) {// 数据不存在
//															// （为第一次调用或数据已过有效期）
//				MarvelsLogUtil.getInstance().info("==========数据不存在或，已失效调用上海资信============");
//				/*
//				 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
//				 */
//				if (PropertiesUtils.isTurnOffForSwitch("switch.shanghaizx001")) {
//					// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
//					returnMap.put("code", RespStatus.DISABLE.getCode() + "");
//					returnMap.put("msg", RespStatus.DISABLE.getMsg());
//					return returnMap;
//				}
//				// 直接查询接口
//				queryDirect(map);
//				// 插入第三方数据调用记录
//				EdcDataCallOperationRecordsDto edcDataCallOperationRecords = new EdcDataCallOperationRecordsDto();
//				edcDataCallOperationRecords.setCustIdCard(custIdCard);
//				edcDataCallOperationRecords.setInterfaceCode(interfaceCode);
//				edcDataCallOperationRecords.setLoanId(map.get("loanId").toString());
//				edcDataCallOperationRecords.setMobile(mobile);
//				edcDataCallOperationRecords.setProductType(productType);
//				edcDataCallOperationRecords.setValidityEndDate(SystemUtil.getAddDay(new Date(),
//						Integer.parseInt(edcProductInterfaceEffecttimeConfigDto.getValidityDate())));
//				saveEdcDataCallOperationRecords(edcDataCallOperationRecords);
//
//				returnMap.put("code", "0000");
//				returnMap.put("msg", "为第一次调用或数据已过有效期，需要对接第三方");
//
//			} else {
//				MarvelsLogUtil.getInstance().info("==========数据属于有效期============");
//				returnMap.put("code", "0000");
//				returnMap.put("msg", "数据属于有限期不需要对接第三方");
//			}
//		}
//		return returnMap;
//	}

	@Override
	public void queryDirect(Map<String, String> map) throws Exception {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		// 鉴于上海资信需要先登陆VPN，再查询接口，并且分开成两个方法来写，比较特殊，所以采用先插入失败记录，后更新的模式来处理。
		String generateOrderNo = generateOrderNo();
		map.put("generateOrderNo", generateOrderNo); // 后面REQ_NO都使用此编号
		saveDataQueryLogNew(generateOrderNo, map.get("loanId"), null, new Date(), null, null,
				LocalStatus.REQUEST_FAIL.getCode(), "edc_shzx_data_query_log", map.get("certno"));
		if ("1".equals(thirdProperties.getShzx_switch())) { // 1走新模式，其它走老模式
			MarvelsLogUtil.getInstance().info("========go new model======");
			HttpClient httpClient = new HttpClient();
			shanghailoginVPN(httpClient);
			queryCredit(map, httpClient);
		} else {
			MarvelsLogUtil.getInstance().info("========old new model======");
			shanghailoginVPN(httpClient);
			queryCredit(map, httpClient);
		}
	}

	// 生成reqNo
	private String generateOrderNo() {
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmsss");
		return "SHZX_" + df.format(new Date()) + "_" + SerialNumCreater.getCharacters(6);
	}

	@Override
	public Map<String, String> queryZxDataInfo(Map<String, String> map) {
		String loanId = map.get("loanId");
		return edcZxPersonalService.queryZxDataInfo(loanId);
	}

	@Override
	public List<Map<String, Object>> queryShZxSituaInfo(String loanId) {
		return edcZxPersonalBaoGaoInfoMapper.queryShZxSituaInfo(loanId);
	}

	@Override
	public EdcZxPersonalLoanOrderInfo queryPersonalLoanOrderInfoByLoanId(String loanId) {
		EdcZxPersonalLoanOrderInfo info = this.edcZxPersonalBaoGaoInfoMapper.queryPersonalLoanOrderInfoByLoanId(loanId);
		return info;
	}

}
